package com.beasu.tingting.ui.main

import android.content.*
import android.os.Bundle
import android.os.IBinder
import android.preference.PreferenceManager
import android.util.Log
import android.view.*
import androidx.fragment.app.Fragment
import androidx.databinding.DataBindingUtil
import androidx.lifecycle.Observer
import androidx.lifecycle.ViewModelProvider
import com.beasu.tingting.R
import com.beasu.tingting.databinding.MainFragmentBinding
import com.beasu.tingting.services.MusicService
import com.beasu.tingting.services.SingleService
import com.beasu.tingting.utils.Wave
import kotlinx.coroutines.InternalCoroutinesApi
import kotlinx.coroutines.internal.synchronized
import java.lang.Exception
import java.util.*
import kotlin.concurrent.thread

class MainFragment : Fragment(), View.OnClickListener,
    SharedPreferences.OnSharedPreferenceChangeListener {

    companion object {
        fun newInstance() = MainFragment()
    }

    private lateinit var viewModel: MainViewModel
    private lateinit var binding: MainFragmentBinding
    private var binder: MusicService.MusicBinder? = null
    private var singleBinder: SingleService.SingleBinder? = null
    private var mainactivity: Context? = null
    private val conn = MusicConnection()
    private val singleConn by lazy {
        SingleConnection()
    }

    override fun onCreateView(
        inflater: LayoutInflater, container: ViewGroup?,
        savedInstanceState: Bundle?
    ): View {
        binding = DataBindingUtil.inflate(inflater, R.layout.main_fragment, container, false)
        return binding.root
    }

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        Log.i("fragment", "onCreate")
        setHasOptionsMenu(true)
    }

    override fun onDestroy() {
        super.onDestroy()
        Log.i("fragment", "onDestroy")
    }

    override fun onAttach(context: Context) {
        super.onAttach(context)
        this.mainactivity = context
        Log.i("fragment", "onAttach")

    }

    override fun onDetach() {
        super.onDetach()
        //  mainactivity?.stopService(Intent(mainactivity, MusicService::class.java))
        //      mainactivity?.unbindService(conn)
        mainactivity?.stopService(Intent(mainactivity, SingleService::class.java))
        mainactivity?.unbindService(singleConn)
        mainactivity = null
    }

    override fun onActivityCreated(savedInstanceState: Bundle?) {
        super.onActivityCreated(savedInstanceState)

//        binding.pauseBtn.setOnClickListener(View.OnClickListener {
//            binder?.play()
//            Log.i("pauseBtn","播放音乐")
//        })
//        val intent  = Intent(mainactivity, MusicService::class.java)
//        mainactivity?.startService(intent)
//        mainactivity?.bindService(intent,conn,0)

        val intent = Intent(mainactivity, SingleService::class.java)
        mainactivity?.startService(intent)
        mainactivity?.bindService(intent, singleConn, 0)
        var shp = PreferenceManager.getDefaultSharedPreferences(mainactivity)
        shp.registerOnSharedPreferenceChangeListener(this)
        try {
            //freq = shp.getString("di_frequency", "1000")!!.toInt()
            //time = shp.getString("time", "50")!!.toInt()
            viewModel.di_frequency.value = shp?.getString("di_frequency", "1000")!!.toInt()
            viewModel.da_frequency.value = shp?.getString("da_frequency", "1000")!!.toInt()
        } catch (e: Exception) {
            e.printStackTrace()
        }

        binding.imageButtonPlay.setOnClickListener(this)
        viewModel = ViewModelProvider(this).get(MainViewModel::class.java)

        viewModel.textString.observe(viewLifecycleOwner, Observer<String> {
            Log.i("textString", it)
        })
        viewModel.di_frequency.observe(viewLifecycleOwner, Observer {
            viewModel.calcDiWave()
        })
        viewModel.da_frequency.observe(viewLifecycleOwner, Observer {
            viewModel.calcDaWave()
        })
        viewModel.time.observe(viewLifecycleOwner, Observer {
            viewModel.calcDaWave()
            viewModel.calcDiWave()
            viewModel.cakcBlankWave()
        })
        Log.i("lifecycleOwner", binding.lifecycleOwner.toString())
        binding.viewModel = viewModel
        binding.lifecycleOwner = this
        Log.i("lifecycleOwner", binding.lifecycleOwner.toString())

    }

    override fun onCreateOptionsMenu(menu: Menu, inflater: MenuInflater) {
        super.onCreateOptionsMenu(menu, inflater)
        inflater.inflate(R.menu.mainmenu, menu)
    }

    inner class MusicConnection : ServiceConnection {
        override fun onServiceDisconnected(name: ComponentName?) {
            Log.i("Disconnected", name.toString())
        }

        override fun onServiceConnected(name: ComponentName?, service: IBinder?) {
            Log.i("connect", "连接")
            binder = service as MusicService.MusicBinder
        }
    }

    inner class SingleConnection : ServiceConnection {
        override fun onServiceDisconnected(name: ComponentName?) {
        }

        override fun onServiceConnected(name: ComponentName?, service: IBinder?) {
            singleBinder = service as SingleService.SingleBinder?
        }
    }
    @Volatile
    private  var ok = false
      override fun onClick(v: View?) {
        when (v?.id) {

            R.id.imageButtonPlay -> {
                Log.i(
                    "wave",
                    "[${viewModel.di_frequency},${viewModel.da_frequency},${viewModel.time}]"
                )
                if(ok){
                    return
                }
                ok =true
              //  Log.i("wave", "[$freq,$time]")
                val diwave = viewModel.diWave
                val dawave = viewModel.daWave
                val blankwave = viewModel.blankWave

                val smalBlankWave = viewModel.smalBlankWave


                Thread(
                    Runnable {
                        for (c in viewModel.morseCodeString.value!!) {
                            if (c.equals('.')) {
                                singleBinder?.play(diwave)
                                singleBinder?.play(smalBlankWave)
                            } else if (c.equals('-')) {
                                singleBinder?.play(dawave)
                                singleBinder?.play(smalBlankWave)
                            } else if (c.equals(' ')) {
                                singleBinder?.play(blankwave)
                            }
                        }
                        ok = false
                    }
                ).start()

            }
        }
    }
    override fun onSharedPreferenceChanged(sharedPreferences: SharedPreferences?, key: String?) {
        //freq = sharedPreferences?.getString("di_frequency", "1000")!!.toInt()
        viewModel.di_frequency.value = sharedPreferences?.getString("di_frequency", "1000")!!.toInt()
        viewModel.da_frequency.value = sharedPreferences?.getString("da_frequency", "1000")!!.toInt()
        viewModel.time.value = sharedPreferences.getString("time", "50")!!.toInt()
        //time = sharedPreferences?.getString("time", "50")!!.toInt()
    }
}
